package cn.itcast.store.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.store.domain.Category;
import cn.itcast.store.domain.User;
import cn.itcast.store.service.CategoryService;
import cn.itcast.store.service.serviceImp.CategoryServiceImp;
import cn.itcast.store.utils.MyBeanUtils;
import cn.itcast.store.utils.UUIDUtils;
import cn.itcast.store.web.base.BaseServlet;

public class AdminCategoryServlet extends BaseServlet {

	// 默认方法
	public String findAll(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException, Exception {

		CategoryService categoryService = new CategoryServiceImp();

		List<Category> findAllCats = categoryService.findAllCats();

		req.setAttribute("list", findAllCats);

		return "/admin/category/list.jsp";
	}

	// addCategoryUI
	public String addCategoryUI(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		return "/admin/category/add.jsp";
	}
	
	public String deleteCategory(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String cid = req.getParameter("cid");
		CategoryService categoryService = new CategoryServiceImp();
		categoryService.deleteCategory(cid);
		resp.sendRedirect("/shopping/AdminCategoryServlet?method=findAll");
		return "null";
	}
	
	
	public String EditSaveCategory(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		//String cid = req.getParameter("cid");
		Category Category=MyBeanUtils.populate(Category.class, req.getParameterMap());
		System.out.println(Category);
		CategoryService categoryService = new CategoryServiceImp();
		categoryService.EditSaveCategory(Category);
		resp.sendRedirect("/shopping/AdminCategoryServlet?method=findAll");
		return "null";
	}
	public String editCategoryUI(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		
		String cid = req.getParameter("cid");
		//System.out.println(cid);
		CategoryService categoryService = new CategoryServiceImp();
		
		Category Category =categoryService.findCategoryByCid(cid);
		req.setAttribute("Category", Category);
		
		return "/admin/category/edit.jsp";
	}

	public String addCategory(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String cname = req.getParameter("cname");
		String cid = UUIDUtils.getId();
		
		Category c=new Category();
		c.setCid(cid);
		c.setCname(cname);
		
		CategoryService CategoryService=new CategoryServiceImp();
		CategoryService.addCategory(c);
		//重定向到查询全部分类信息
		resp.sendRedirect("/shopping/AdminCategoryServlet?method=findAll");
		return null;
	}

}
